﻿//时间轴默认位置-top
const DEFALUT_TIMESHAFT_TOP = 23;
//时间轴默认位置-right
const DEFALUT_TIMESHAFT_RIGHT = -28;
//最大总月份数
const MAX_TIMESHAFT_MONTH = 7;

$(function () {
    $("input[type=radio]").cssRadio();
    $("input[type=checkbox]").cssCheckBox();
    $("table.cisa_tabel_default").tabelscroll();
    $(".search_footer_contain>div.btn_group").cssCenter({
        margin: "10px auto"
    });
    //设置某个元素居中
    //$(".search_footer_contain>div.btn_group").cssCenter({
    //    margin:"50px auto"
    //});
});

(function ($) {
    $.fn.cssRadio = function () {//设置Radio样式为自定义样式
        var div = document.createElement("div");
        var name = $(this).attr("name");
        $(div).addClass("cisa_radio");
        $(div).attr("name", name);
        var lable = document.createElement("lable")
        $(this).wrap(div);
        $(this).after(lable);
        $("div[name=" + name + "]>lable").click(function () {
            $("div[name=" + name + "]>lable").removeClass("checked");
            $("div[name=" + name + "]>input").removeAttr("checked");
            $(this).parent().find("input").attr("checked", "checked");
            $(this).addClass("checked");
        });
    };
    $.fn.cssCheckBox = function () {//设置CheckBox为自定义样式
        var div = document.createElement("div");
        var name = $(this).attr("name");
        $(div).addClass("cisa_checkbox");
        $(div).attr("name", name);
        var lable = document.createElement("lable")
        $(this).wrap(div);
        $(this).after(lable);
        $("div.cisa_checkbox>lable").click(function () {
            $(this).toggleClass("checked");
            var checkBox = $(this).parent().find("input");
            if ($(this).hasClass("checked")) {
                $(checkBox).attr("checked", "checked");
            } else {
                $(checkBox).removeAttr("checked");
            }
        });
    }
    $.fn.cssCenter = function (options) {//设置样式居中
        var defaultVal = {
            margin: "0px auto"
        }
        var obj = $.extend(defaultVal, options);
        return this.each(function () {
            var nowObj = $(this);
            setAutoWidth(nowObj);
            $(nowObj).css("margin", obj.margin);
        });
    }
    $.fn.cssCenter = function (options) {//设置样式居中
        var defaultVal = {
            margin: "0px auto"
        }
        var obj = $.extend(defaultVal, options);
        return this.each(function () {
            var nowObj = $(this);
            setAutoWidth(nowObj);
            $(nowObj).css("margin", obj.margin);
        });
    }
    $.fn.cssAbsoluteCenter = function (isAnimate) {//设置绝对居中
        var child = $(this);
        if (typeof (parent) == "undefined" || typeof (child) == "undefined")
            return;
        var top_value = Math.abs($(window).height() - $(child).height()) / 2;
        var left_value = Math.abs($(window).width() - $(child).width()) / 2;
        top_value = top_value + "px";
        $(this).css({
            "top": "0px",
            "left": left_value + "px"
        })
        if (isAnimate) {
            $(this).animate({
                "top": top_value
            }, "slow");
            return;
        }

        $(this).css({
            "top": top_value
        }, "slow");

    }
    $.fn.tabelscroll = function () {//控制表格横向滚动条
        return this.each(function () {
            var table_width = $(this).width() + parseInt($(this).css("margin-left")) + parseInt($(this).css("margin-right"));
            var wrap = $(this).parent();
            var wrap_width = $(wrap).width();
            if (table_width > wrap_width) {
                $(wrap).css("overflow-x", "scroll");
            }
        });
    }
    $.fn.addYearMothDay = function (option) {
        var defaultVal = {
            min: 1890,
            max: 2100,
            step: 1,
            text: "" //数字后的文本
        }
        var obj = $.extend(defaultVal, option);
        var i = obj.min;
        while (i <= obj.max) {
            var option = document.createElement("option");
            option.text = i + obj.text;
            option.value = i;
            $(this).append(option);
            i = i + obj.step;
        }
    }
    /*****************************
    $("#timeShaft").timeShaft({
        month: 5, //选中的月份
        year: 2015, //选中的年份
        func: function () { //点击后的事件
            $.alertPopup({
                content: "测试"
            })
        },
        position:{ //时间轴的位置（可选参数）
            top: 15,
            right:18
        }
    });
    *****************************/
    $.fn.timeShaft = function (option) {
        var defaultVal = {
            month: new Date().getMonth() + 1,
            year: new Date().getFullYear(),
            func: function () {

            },
            position: {
                top: DEFALUT_TIMESHAFT_TOP,
                right: DEFALUT_TIMESHAFT_RIGHT
            },
            containerSelector: "null"
        }
        var obj = $.extend(defaultVal, option);
        if (obj.month == null) {
            obj.month = new Date().getMonth() + 1;
        }
        if (obj.year == null) {
            obj.year = new Date().getFullYear();
        }
        var timeShaft = $(this);
        $(timeShaft).addClass("time_shaft").css({
            "top": obj.position.top + "px",
            "right": obj.position.right + "px"
        });
        if (!typeof (obj.position.left) == "undefined") {
            $(timeShaft).css({
                "left": obj.position.left + "px"
            })
        }
        getTimeShaft($(this), obj.year, obj.month, obj.func);
        if (obj.containerSelector != "null" && obj.containerSelector != "undefined") {
            $(timeShaft).pin({
                containerSelector: obj.containerSelector,
                minWidth: 940
            })
        }
        //生成时间轴的方法
        /*
         obj 时间轴主体
         year,month 为选中的年月
         func 点击时间轴执行的回调事件
        */
        function getTimeShaft(obj, year, month, func) {
            var $timeShaft = $("div.time_shaft");
            var Def_Month = month;
            var Def_year = year;
            $timeShaft.empty();
            //时间轴的线
            var line = "<div class=\"line\" style=\"height:355px;\"></div>";
            $timeShaft.prepend(line);
            var ul = document.createElement("ul");
            var li = document.createElement("li");
            month = Def_Month - 3;
            switch (month) {
                case 0: month = 12;
                    year = year - 1;
                    break;
                case -1: month = 11;
                    year = year - 1;
                    break;
                case -2: month = 10;
                    year = year - 1;
                    break;
            }
            for (var i = 0 ; i < MAX_TIMESHAFT_MONTH; i++) {
                var yearDom = returnYearDom(year);
                var monthDom = "<li  year=\"" + year + "\" month=\"" + month + "\">" +
                                "      <a class=\"btn btn_sm btn_time_shaft_btn\">" + month + "月</a>" +
                                "</li>";
                if (i == 0) {
                    $(ul).append(yearDom);
                }
                if (month == 12) {
                    $(ul).append(monthDom);
                    month = 1;
                    yearDom = returnYearDom(++year);
                    $(ul).append(yearDom);
                } else {
                    $(ul).append(monthDom);
                    month++;
                }
            }
            $timeShaft.append(ul);
            $ul = $timeShaft.find("ul");
            //为选中月份添加样式
            $ul.find("li").filter("[year = " + Def_year + "][month =" + Def_Month + "]").children("a").removeClass("btn_time_shaft_btn").addClass("btn_time_shaft_btn_choose");
            $ul.find("li").filter("[month]").children("a").click(function () {
                var timeShaft = $(this).parent().parent(),
                    $li = $(this).parent();
                var year = $li.attr("year"),
                    month = $li.attr("month");
                getTimeShaft(timeShaft, year, month, func);
            });
            $ul.find("li").filter("[month]").children("a").click(func);
            //为当前选中月份tian
            function returnYearDom(year) {
                return "<li>" +
                        "    <a class=\"btn btn_sm btn_time_shaft_year_btn\">" + year + "年</a>" +
                        "</li>";
            }
        }
    }
    /***********
     $("#query_table").createTable({
            table: "query_table", //tableId
            data: json.rows,//json数据
            cname: { //显示字段
                'username': [],
                'password': [],
                'male': [
                    { key: "0", value: "男" },
                    { key: "1", value: "女" }
                ],
                'age': []
            },
            hiddenField: { //隐藏字段
                'id': []
            },
            buttons: [{ //按钮及按钮事件
                id: 'details',
                style: 'btn btn_table_xs',
                content: '<i class="icon-search" title="查看详情"></i>',
                hasSplit:"false", //不传默认为false
                func: function () {
                    alert("呵呵");
                }
            }, {
                id: 'edit',
                style: 'btn btn_table_xs',
                content: '<i class="icon-pencil" title="编辑"></i>',
                hasSplit: "false",
                func: function () {
                   
                }
            }, {
                id: 'delete',
                style:'btn_href_blue', //文字样式
                content: '删除',
                func: function () { //按钮回调事件
                    var id = $(this).parents("tr").first().find("input[name=id]").val();
                    $.alertPopup({
                        content: id
                    })
                }
            }]
        });
    *************/
    $.fn.createTable = function (options) {
        $(this).show();
        var table = $("#" + options.table);
        var tbody = $(table).find("tbody");
        tbody.empty();
        //每项数据key名称
        var cnameKey = new Array();
        for (var key in options.cname) {
            cnameKey.push(key);
        }
        if (typeof (options.buttons) != "undefined") { //操作按钮栏
            const oprateKey = "operate"; //定义表单操作td的name
            cnameKey.push(oprateKey); //添加操作按钮的占位
            var thead = $(this).find("thead");
            var tr = $(thead).find("tr");
            if (!$(thead).find("#table_oprate").length > 0) { //第一次执行则在头部添加一列
                var th = $('<th id="table_oprate">操作</th>');
                $(tr).append(th);
            }
        }
        //隐藏域
        var hiddenKey = new Array();
        for (var key in options.hiddenField) {
            hiddenKey.push(key);
        }
        $.each(options.data, function (n, v) {
            var row = $(document.createElement("tr"));
            $.each(cnameKey, function (a, b) {
                var td = $(document.createElement("td"));
                if (b == oprateKey) { //有操作按钮栏
                    td.attr("name", oprateKey);
                    $.each(options.buttons, function (m, n) {
                        var btn = document.createElement("a");
                        $(btn).addClass(n.style);//为按钮添加样式
                        $(btn).append(n.content);//添加按钮文本
                        $(btn).click(n.func);
                        if (n.hasSplit == "true") {
                            $(td).append(btn).append("<span>|</span>");
                        } else {
                            $(td).append(btn);
                        }
                    });
                    row.append(td);
                    return;
                }
                td.attr("name", b);
                td.text(function () {
                    var r = "";
                    if (typeof ("v." + b) == "undefined" || eval("v." + b) == "") { //非空判断
                        r = "-";
                        return r;
                    }
                    $.each(eval("options.cname." + b), function (q, w) {//转义判断
                        if (eval("v." + b) == w.key) {
                            r = w.value;
                            return r;
                        }
                    });
                    if (r == "") { //如果没转义也不是undifined 则将传进来的值填入
                        r = eval("v." + b);
                    }
                    if (r == null) { //如果后台传过来的值为null 则转换为"-"
                        r = "-";
                    }
                    return r.toString();
                });
                if (a == 0) {//将隐藏域放在第一列
                    $.each(hiddenKey, function (hiddenInd, hiddenVal) {
                        var input = $(document.createElement("input"));
                        input.attr("type", "hidden");
                        input.attr("name", hiddenVal);
                        input.val(function () {
                            var r = "";
                            if (typeof (eval("v." + hiddenVal)) == "undefined" || eval("v." + hiddenVal) == "") {
                                r = "-";
                                return r;
                            }
                            $.each(eval("options.hiddenField." + hiddenVal), function (q, w) {//转义判断
                                if (eval("v." + hiddenVal) == w.key) {
                                    r = w.value;
                                    return r;
                                }
                            });
                            if (r == "") {
                                r = eval("v." + hiddenVal);
                            }
                            return r.toString();
                        });
                        td.append(input);
                    })
                }
                row.append(td);
            });
            tbody.append(row);
        });
    };
    $.extend({
        /********
           ===========结构==============
                 <div class="popup_msg">
                    <div class="popup_wrap">
                        <div class="popup_header">
                            <span class="popup_title">
                                    <i class="icon-bubbles3"></i>
                                    系统提示
                            </span>
                            <span class="popup_msg_close"></span>
                        </div>
                        <div class="popup_contain">
                            确认进行此操作么?
                        </div>
                        <div class="popup_footer">
                            <div style="width: 248px; margin: 0px auto;">
                                <button class="btn btn_blue_sm">确认</button>
                                <button class="btn btn_blue_sm">取消</button>
                            </div>
                        </div>
                    </div>
                    <div class="popup_back"></div>
                </div>
        **********/
        confirmPopup: function (options) {
            var defaultVal = {
                icon: "icon-bubbles3", //图标
                title: "系统提示",//标题
                contain: "确认进行此操作么?", //内容
                btn: {
                    left: "取消",//左侧按钮
                    right: "确认"//右侧按钮
                },
                hasBack: true,//有无背景
                hasCloseBtn: true,//有无关闭按钮
                isSport: false, //有无动画
                func_Close: null,//关闭按钮回调方法
                func_Left: null,//左侧按钮回调方法
                func_Right: null//右侧按钮回调方法
            }
            var obj = $.extend(defaultVal, options);
            var popup_msg = document.createElement("div");//主层
            $(popup_msg).addClass("popup_msg");
            var popup_header = document.createElement("div");//主体头部层
            $(popup_header).addClass("popup_header");
            var span_title = document.createElement("span");//标题
            var icon = document.createElement("i");//标题图标
            $(icon).addClass(obj.icon);//添加图标
            $(span_title).addClass("popup_title").append(icon).append(obj.title);//添加标题
            if (obj.hasCloseBtn) {
                var span_close = document.createElement("span");//关闭按钮
                $(span_close).addClass("popup_msg_close");
                $(span_close).click(function () {
                    $("div.popup_msg").remove();
                    obj.func_Close && obj.func_Close();
                });
            }
            $(popup_header).append(span_title).append(span_close);//将标题添加到头部
            var popup_contain = document.createElement("div");//主体内容层
            $(popup_contain).addClass("popup_contain");
            $(popup_contain).append(obj.contain);//将内容文字添加到内容
            var popup_footer = document.createElement("div");//底部按钮层
            $(popup_footer).addClass("popup_footer");
            var div = document.createElement("div");//按钮包裹层
            var btn_enter = document.createElement("button");//确定按钮
            $(btn_enter).addClass("btn btn_blue_sm");
            $(btn_enter).append(obj.btn.left);
            $(btn_enter).click(function () {
                $("div.popup_msg").remove();
                obj.func_Left && obj.func_Left();
            });
            var btn_cancel = document.createElement("button");//取消按钮
            $(btn_cancel).addClass("btn btn_blue_sm");
            $(btn_cancel).append(obj.btn.right);
            $(btn_cancel).click(function () {
                $("div.popup_msg").remove();
                obj.func_Right && obj.func_Right();
            });
            $(div).append(btn_enter).append(btn_cancel);//将按钮添加到按钮包裹层
            $(popup_footer).append(div);
            var popup_wrap = document.createElement("div");//主体wrap层
            $(popup_wrap).addClass("popup_wrap");
            $(popup_wrap).append(popup_header);//将头部添加到wrap层
            $(popup_wrap).append(popup_contain);//将内容添加到wrap层
            $(popup_wrap).append(popup_footer);//将底部按钮层添加到wrap层
            $(popup_msg).append(popup_wrap);//添加主体
            if (obj.hasBack) {
                var popup_back = document.createElement("div");//背景层
                $(popup_back).addClass("popup_back");
                $(popup_msg).append(popup_back);//添加背景层 
            }
            $("body").append(popup_msg);//将popup添加到页面
            $(div).cssCenter();//居中按钮包裹层
            $(popup_wrap).cssAbsoluteCenter(obj.isSport);//设置居中
        },
        /***
          ============结构====================
          <div class="popup_msg">
                <div class="popup_wrap">
                    <div class="popup_header">
                        <span class="popup_title">
                            <i class="icon-bubbles3"></i>
                            系统提示
                        </span>
                        <span class="popup_msg_close"></span>
                    </div>
                    <div class="popup_contain">
                        确认进行此操作么?
                    </div>
                </div>
                <div class="popup_back"></div>
            </div>
        ***/
        alertPopup: function (options) {
            var defaultVal = {
                icon: "icon-bubbles3", //图标
                title: "系统提示",//标题
                content: "", //内容
                hasBack: true,//有无背景
                isSport: false,//有无动画效果
                func_close: null//关闭按钮回调方法
            }
            var obj = $.extend(defaultVal, options);
            var popup_msg = document.createElement("div");//主层
            $(popup_msg).addClass("popup_msg");
            var popup_header = document.createElement("div");//主体头部层
            $(popup_header).addClass("popup_header");
            var span_title = document.createElement("span");//标题
            $(span_title).addClass("popup_title");
            var icon = document.createElement("i");//标题图标
            $(icon).addClass(obj.icon);//添加图标
            $(span_title).append(icon).append(obj.title);//添加标题
            var span_close = document.createElement("span");//关闭按钮
            $(span_close).addClass("popup_msg_close");
            $(popup_header).append(span_title).append(span_close);//将标题添加到头部
            $(span_close).click(function () {
                $("div.popup_msg").remove();
                obj.func_close && obj.func_close();
            });
            var popup_contain = document.createElement("div");//主体内容层
            $(popup_contain).addClass("popup_contain");
            $(popup_contain).append(obj.content);//将内容文字添加到内容
            var popup_wrap = document.createElement("div");//主体wrap层
            $(popup_wrap).addClass("popup_wrap");
            $(popup_wrap).append(popup_header);//将头部添加到wrap层
            $(popup_wrap).append(popup_contain);//将内容添加到wrap层
            $(popup_msg).append(popup_wrap);//添加主体
            if (obj.hasBack) {
                var popup_back = document.createElement("div");//背景层
                $(popup_back).addClass("popup_back");
                $(popup_msg).append(popup_back);//添加背景层 
            }
            $("body").append(popup_msg);//将popup添加到页面
            $(popup_wrap).cssAbsoluteCenter(obj.isSport);//设置居中
        }
    });
})(jQuery);


function setAutoWidth(obj) { //设置obj的宽度为其所有子元素宽度之和
    var width = 0
    $(obj).children().each(function () {
        width += parseInt($(this).outerWidth(true));
        if ($(this).css("display") == "inline-block") { //使用display属性代替float的时候将会产生4px的空白
            width += 4;
        }
    });
    $(obj).css("width", width + "px");
}